package ch.fhnw.qualiscan.application.models;

import java.util.ArrayList;
import java.util.List;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.core.Model;
import ch.fhnw.qualiscan.core.db.pojos.Role;
import ch.fhnw.qualiscan.core.db.pojos.RoleText;
import ch.fhnw.qualiscan.core.db.pojos.Survey;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.helpers.SessionHelper;

public class RoleModel extends Model {
	
	/**
	 * This function returns all roles in the survey.
	 * @param currentSurvey 
	 * @return List containing RoleText objects
	 */
	public ArrayList<Role> getRoles(Survey currentSurvey) {
		
		UserModel userModel = new UserModel();
		SessionHelper sessionHelper = new SessionHelper();
		Role roleExpert = new Role();
		roleExpert.setId(Config.EXPERT_ID);
		@SuppressWarnings("unchecked")
		List<SurveyUserRole> rolesInSurvey = hibernateSession.getSession().createQuery("from SurveyUserRole as sur WHERE surveyId = :surveyId and role != :roleE GROUP BY sur.role")
		.setParameter("surveyId", currentSurvey.getId())
		.setParameter("roleE", roleExpert)
		.list();
		
		ArrayList<Role> roles = new ArrayList<Role>();
		
		Role coordinatorRole = null;
		
		for(SurveyUserRole o : rolesInSurvey) {
			if (o.getRole().getId() == Config.COORDINATOR_ID) {
				coordinatorRole = o.getFillOutRole();
			}
			else {
				roles.add(o.getRole());
			}
		}
		
		if (coordinatorRole != null) {
			if (!roles.contains(coordinatorRole)) {
				roles.add(coordinatorRole);
			}
		}
		
		return roles;
	}
	
	/**
	 * Gets all roles which are important from a cordinators point of view. Excludes cordinator and administrator.
	 * @return List of roles
	 */
	public List<Role> getParticipantRoles() {
		List<Role> roles = hibernateSession.getSession().createQuery("from Role").list();
		List<Role> removeRoles = new ArrayList<Role>();
		
		for(Role o : roles) {
			if(o.getId() == Config.ADMINISTRATOR_ID || o.getId() == Config.COORDINATOR_ID)
				removeRoles.add(o);
		}
		
		// remove roles
		for(Role o : removeRoles) {
			roles.remove(o);
		}
		
		return roles;
	}
	
	/**
	 * Gets the role by its roleId
	 * @param roleId id of the role
	 * @return role
	 */
	public Role getRoleById(int roleId) {
		Role role = (Role) hibernateSession.getSession().createQuery("from Role as role where id = :id")
		.setParameter("id", roleId)
		.uniqueResult();
		
		return role;
	}
	
}
